package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.Movement;
import com.tanhua.domain.mongo.MovementFriend;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class MovementFriendImpl {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveTimeLine(Movement movement){
        //        3、查询当前登录人的好友  1万个好友
//        sql: select * from friend where userId=??   1毫秒
        Query query = new Query(Criteria.where("userId").is(movement.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
//        4、保存movement_firend_USERID(时间线表)
//        假如当前登录人是1号用户， 1号用户的好友是2号 3号 4号
//        movement_firend_2  movement_firend_3  movement_firend_4

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!CollectionUtils.isEmpty(friendList)){
            for (Friend friend : friendList) {
                MovementFriend movementFriend = new MovementFriend();
                movementFriend.setId(new ObjectId());
                movementFriend.setUserId(movement.getUserId());
                movementFriend.setMovementId(movement.getId());
                movementFriend.setCreated(new Date().getTime());
                mongoTemplate.save(movementFriend,"movement_friend_"+friend.getFriendId());   //10s
            }

        }
    }

}
